<?php

namespace App\Domain\ApplicationCenter\Services;

use App\Domain\ApplicationCenter\Dao\ApplicationCenterDao;
use App\Domain\ApplicationCenter\Models\ApplicationCenterModel;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use App\Exceptions\BadRequestException;

class ApplicationCenterService
{
    public function create($param)
    {
        $appDao = new ApplicationCenterDao();
        $data = $appDao->findByName($param['name']);
        if ($param['name'] === $data['name']) {
            throw new BadRequestException('应用已存在');
        }
        $res = $appDao->create([
            'name' => $param['name'],
            'icon' => $param['icon'],
            'language_arousal' => $param['language_arousal'],
            'startup_parameter' => $param['startup_parameter'],
            'download_url' => $param['download_url'],
            'description' => $param['description'],
            'sort' => $param['sort']
        ]);
        return $res;
    }

    /**
     * 应用列表
     * @param $params
     * @return LengthAwarePaginator|Builder[]|Collection
     */
    public function list($params)
    {
        $query = ApplicationCenterModel::query()
            ->select('application_center.*')
            ->where('application_center.state', 1);
        $query = $query->where(function (Builder $query) use ($params) {
            if (isset($params['name']))
                $query->where('name', 'like', "%{$params['name']}%");
        });
        if (isset($params['pageSize']) && isset($params['currentPage'])) {
            return $query->paginate($params['pageSize'], ['*'], 'page', $params['currentPage']);
        } else {
            return $query->get();
        }
    }

    //应用删除
    public function del($id)
    {
        $app = new ApplicationCenterDao();
        $data = $app->del($id);
        return $data;
    }

    //应用更改
    public function update($param)
    {
        $appDao = new ApplicationCenterDao();
        $data = $appDao->findById($param['id']);
        if(empty($data)){
             throw new BadRequestException('应用不存在');
        }
        $res = $appDao->update($data,$param);
        return $res;
    }
}
